//
//  BEGoogleMapsViewController.swift
//  BEGlobalOiler
//
//  Created by KKING on 16/8/18.
//  Copyright © 2016年 Bullseye Energy pte ltd. All rights reserved.
//

import UIKit
import GoogleMaps
import SnapKit
//import MapKit


class BEGoogleMapsViewController: UIViewController {
    
    var markerImed:GMSMarker = GMSMarker()
    private var mapViewImed:GMSMapView = GMSMapView()
    
    var locationManager:CLLocationManager = {
        let locationManager = CLLocationManager()
        return locationManager
    }()
    
    var addressView:BEAddressView = {
        let addressView = BEAddressView.addressView() as! BEAddressView
        return addressView
    }()
    
    
    @objc func DismissMap(){
        _ = navigationController?.popViewController(animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        weak var weakSelf = self
        addressView.dismissMapBlock = {
            () -> () in
            _ = weakSelf?.navigationController?.popViewController(animated: true)
        }        
        
        view.backgroundColor = UIColor.white
        
        //        view = appleMapView
        //        appleMapView.delegate = self
        if locationManager.location == nil {
            return
        }
        
        let camera = GMSCameraPosition.camera(withTarget: (locationManager.location?.coordinate)!, zoom: 12)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        mapView.isMyLocationEnabled = true
        view.addSubview(mapView)
        mapView.delegate = self
        mapViewImed = mapView
        
        setupAddressView()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    private func setupAddressView(){
        
        view.insertSubview(addressView, aboveSubview: view)
        
        let location = self.locationManager.location
        let geocoder = CLGeocoder()
        
        weak var weakSelf = self
        
        geocoder.reverseGeocodeLocation(location!, completionHandler: {
            placemarks, error in
            if error != nil {
                print("Geocode failed with error: \(error!.localizedDescription)")
            }
            
            if placemarks!.count > 0 {
                let placemark: CLPlacemark = (placemarks?.first)!
                let addressDictionary = placemark.addressDictionary
                
                let address     = addressDictionary!["Street"] as? String
                let city        = addressDictionary!["SubLocality"] as? String
                let state       = addressDictionary!["State"] as? String
                
                weakSelf?.addressView.getAddressWithCoordinateBlock = { (addressTF: UITextField,cityTF: UITextField,stateTF: UITextField) -> () in
                    addressTF.text = address
                    cityTF.text = city
                    stateTF.text = state
                }
                weakSelf?.addressView.currentLocation()
            }
        })
        addressView.snp.makeConstraints { (make) in
            make.top.equalTo(64)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(200)
        }
        
        mapViewImed.snp.makeConstraints { (make) in
            make.top.equalTo((weakSelf?.addressView.snp.bottom)!)
            make.left.right.equalTo(0)
            make.bottom.equalTo(0)
        }
    }
}

//谷歌地图代理方法
extension BEGoogleMapsViewController:GMSMapViewDelegate{
    //google地图代理方法 --> 点击地图对应位置.
    func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
        //coordinate - latitude: 31.212245172559406, longitude: 121.30247555673121把当前经纬度处增加一个大头针.
        markerImed.map = nil
        //在对应位置增加marker
        let marker = GMSMarker(position: coordinate)
        marker.appearAnimation = kGMSMarkerAnimationPop
        marker.map = mapView
        markerImed = marker
        
        let geocoder = CLGeocoder()
        let markerlocation = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
        //给marker增加标题和副标题
        
        geocoder.reverseGeocodeLocation(markerlocation, completionHandler: {
            placemarks, error in
            if error != nil {
                print("Geocode failed with error: \(error!.localizedDescription)")
            }
            if placemarks!.count > 0 {
                let placemark: CLPlacemark = (placemarks?.first)!
                let addressDictionary = placemark.addressDictionary
                
                let address     = addressDictionary!["Street"] as? String
                let city        = addressDictionary!["SubLocality"] as? String
                let state       = addressDictionary!["State"] as? String
                
                marker.title = city
                marker.snippet = address
                
                self.addressView.getAddressWithCoordinateBlock = { (addressTF: UITextField,cityTF: UITextField,stateTF: UITextField) -> () in
                    
                    addressTF.text = address
                    cityTF.text = city
                    stateTF.text = state
                }
                NotificationCenter.default.post(name: Notification.Name(rawValue: SubmitAddress), object: nil,userInfo: ["address": "\(state ?? "")" + "\(city ?? "")" + "\(address ?? "")"])
                self.addressView.currentLocation()
            }
        })
    }
}


